using IWshRuntimeLibrary;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 监控
{
    static class Program
    {
        public const uint WM_DROPFILES = 0x0233;
        public const uint MSGFLT_ADD = 1;
        public const ushort VK_A = 0x41;
        public const ushort VK_MENU = 0x12;
        public const ushort VK_RETURN = 0x0D;
        public const uint WM_SYSKEYDOWN = 0x0104;
        public const uint WM_KEYUP = 0x0101;
        public const uint WM_KEYDOWN = 0x0100;
        public const uint SC_CLOSE = 0xF060;
        public const uint WM_COPYDATA = 0x004A;
        public const uint WM_CLOSE = 0x0010;
        public const uint WM_PAINT = 0x000F;
        public const uint WM_QUIT = 0x0012;

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool BringWindowToTop(IntPtr hWnd);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool IsWindowVisible(IntPtr hWnd);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        [DllImport("User32.dll", SetLastError = true)]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        [DllImport("User32.dll", SetLastError = true)]
        public static extern bool IsHungAppWindow(IntPtr hwnd);
        [DllImport("User32.dll", SetLastError = true)]
        public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult);

        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                if (!System.IO.File.Exists(Path.GetFileName(Application.ExecutablePath) + ".config"))
                {
                    System.IO.File.WriteAllText(Path.GetFileName(Application.ExecutablePath) + ".config", Properties.Resources.监控);
                    RegistryAutoStart(true);
                    CreateShortCut();
                }

                Process[] process = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
                if (process.Length > 1)
                {
                    IntPtr window = FindWindow(null, "程序监控");
                    if (window != IntPtr.Zero)
                    {
                        if (!IsWindowVisible(window))
                            ShowWindow(window, 1);
                        SetForegroundWindow(window);
                        BringWindowToTop(window);
                        return;
                    }

                    if (process.Length > 2)
                        return;
                }
                //启动信息
                if (!Directory.Exists("log")) Directory.CreateDirectory("log");
                System.IO.File.AppendAllLines("./log/" + DateTime.Now.ToString("yyyyMMdd") + ".log",
                    new string[] { DateTime.Now + "  start the process monitor" });

                Application.SetHighDpiMode(HighDpiMode.SystemAware);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new FormProc());
            }
            catch (Exception ex)
            {
                if (!Directory.Exists("log")) Directory.CreateDirectory("log");
                System.IO.File.AppendAllLines("./log/" + DateTime.Now.ToString("yyyyMMdd") + ".log",
                    new string[] {
                    DateTime.Now + "  "+  ex.Message,
                    DateTime.Now + "  " + ex.StackTrace
                    });
                Application.Restart();
                Process.GetCurrentProcess().Kill();
            }
        }

        #region 自启动
        static void CreateShortCut()
        {
            try
            {
                WshShell shell = new WshShell();
                string lnkPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "监控程序.lnk");
                IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(lnkPath);//创建快捷方式对象
                shortcut.TargetPath = Application.ExecutablePath;//指定目标路径
                shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);//设置起始位置
                shortcut.WindowStyle = 1;//设置运行方式，默认为常规窗口
                shortcut.Description = "监控程序";//设置备注
                shortcut.IconLocation = Application.ExecutablePath;//设置图标路径
                shortcut.Save();

                string deskPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "监控程序.lnk");
                IWshShortcut desk_shortcut = (IWshShortcut)shell.CreateShortcut(deskPath);//创建快捷方式对象
                desk_shortcut.TargetPath = Application.ExecutablePath;//指定目标路径
                desk_shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);//设置起始位置
                desk_shortcut.WindowStyle = 1;//设置运行方式，默认为常规窗口
                desk_shortcut.Description = "监控程序";//设置备注
                desk_shortcut.IconLocation = Application.ExecutablePath;//设置图标路径
                desk_shortcut.Save();

                if (MessageBox.Show(MessageboxExtension.CloseAfter(10000), "是否创建开机启动快捷方式", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                    System.IO.File.Delete(lnkPath);
            }
            catch { }
        }
        public static bool RegistryAutoStart(bool isAuto)
        {
            try
            {
                RegistryKey R_local = null;
                try
                {
                    R_local = Registry.LocalMachine;
                    R_local.CreateSubKey("SOFTWARE" + (Environment.Is64BitProcess ? "" : @"\WOW6432Node") + @"\Microsoft\Windows\CurrentVersion\Run");
                }
                catch
                {
                    R_local = Registry.CurrentUser;
                }
                using (RegistryKey R_run = R_local.CreateSubKey("SOFTWARE" + (Environment.Is64BitProcess ? "" : @"\WOW6432Node") + @"\Microsoft\Windows\CurrentVersion\Run"))
                {
                    if (isAuto == true)
                        R_run.SetValue(Application.ProductName, "\"" + Application.ExecutablePath + "\"");
                    else
                        R_run.DeleteValue(Application.ProductName, false);
                }

                R_local.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public static bool IsAutoStart()
        {
            RegistryKey RegKey = null;
            try
            {
                RegKey = Registry.LocalMachine;
                RegKey.CreateSubKey("SOFTWARE" + (Environment.Is64BitProcess ? "" : @"\WOW6432Node") + @"\Microsoft\Windows\CurrentVersion\Run").Close();
            }
            catch
            {
                RegKey = Registry.CurrentUser;
            }
            if (RegKey.OpenSubKey("SOFTWARE" + (Environment.Is64BitProcess ? "" : @"\WOW6432Node") + @"\Microsoft\Windows\CurrentVersion\Run").GetValue(Application.ProductName) == null)
                return false;
            else
                return true;
        }
        #endregion
    }
}
